<?php

namespace plugin\ycMassage\utils;

use GuzzleHttp\Client;
use think\facade\Cache;

class BaiduHelper
{
    public static function getAccessToken($config)
    {
        $redis_key = 'yc_massage_baidu_access_token.' .$config['appid'];

        $access_token = Cache::get($redis_key);
        if ($access_token) {
            return $access_token;
        }
        $query = [
            'client_id' => $config['key'],
            'client_secret' => $config['secret'],
            'grant_type' => 'client_credentials'
        ];
        $url = 'https://aip.baidubce.com/oauth/2.0/token?' . http_build_query($query);
        $client = new Client;
        $response = $client->get($url);
        $data = json_decode($response->getBody()->getContents(), true);
        if (isset($data['error'])) {
            throw new \Exception($data['error_description']);
        }
        Cache::set($redis_key, $data['access_token'], $data['expires_in'] - 60);
        return $data['access_token'];
    }
}
